package com.wanlong.sys.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wanlong.sys.dao.SysUserMapper;
import com.wanlong.sys.dao.SysUserRoleMapper;
import com.wanlong.sys.model.SysRole;
import com.wanlong.sys.model.SysUser;
import com.wanlong.sys.model.SysUserRole;
import com.wanlong.sys.service.ISysUserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysUserService implements ISysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    public long insert(SysUser sysUser) {
        sysUserMapper.insertSelective(sysUser);
        //更新角色
        sysUserRoleMapper.cleanById(sysUser.getId());
        for(long roleid : sysUser.getRole()){
            SysUserRole sur = new SysUserRole();
            sur.setUserId(sysUser.getId());
            sur.setRoleId(roleid);
            sysUserRoleMapper.insertSelective(sur);
        }
        return sysUser.getId();
    }

    public int update(SysUser sysUser) {
        int result = sysUserMapper.update(sysUser);
        //更新角色
        sysUserRoleMapper.cleanById(sysUser.getId());
        for(long roleid : sysUser.getRole()){
            SysUserRole sur = new SysUserRole();
            sur.setUserId(sysUser.getId());
            sur.setRoleId(roleid);
            sysUserRoleMapper.insertSelective(sur);
        }
        return result;
    }

    public int delete(SysUser sysUser) {
        return sysUserMapper.delete(sysUser);
    }

    public SysUser getSysUserById(Long id) {
        return sysUserMapper.getById(id);
    }

    public SysUser getSysUserListByName(String loginName) {
        return sysUserMapper.getSysUserByLoginName(loginName);
    }

    public PageInfo<SysUser> getPageSysUserListByName(String loginName, Integer pageNo, Integer pageSize) {
        pageNo = pageNo == null?1:pageNo;
        pageSize = pageSize == null?10:pageSize;
        PageHelper.startPage(pageNo, pageSize);
        List<SysUser> list = sysUserMapper.getSysUserList(loginName);
        //用PageInfo对结果进行包装
        PageInfo<SysUser> page = new PageInfo<SysUser>(list);
        //测试PageInfo全部属性
        System.out.println(page.getPageNum());
        System.out.println(page.getPageSize());
        System.out.println(page.getStartRow());
        System.out.println(page.getEndRow());
        System.out.println(page.getTotal());
        System.out.println(page.getPages());
        System.out.println(page.getFirstPage());
        System.out.println(page.getLastPage());
        System.out.println(page.isHasPreviousPage());
        System.out.println(page.isHasNextPage());
        System.out.println(page.getList());
        return page;
    }


}
